//
//  MSAddCommentDataSource.m
//  MSJD
//
//  Created by xiangbo on 2018/12/10.
//  Copyright © 2018 xiangbo. All rights reserved.
//

#import "MSAddCommentDataSource.h"
#import "MSInputAttachView.h"
#import "MSStarControl.h"
#import "MSUserCenterDataSource.h"
#import "MSUploadImageUtils.h"
#import <Photos/Photos.h>

static NSInteger MinCommentLength = 10;
static NSInteger MaxCommentLength = 600;

@interface MSAddCommentDataSource ()<UIScrollViewDelegate, MSInputAttachViewDelegate, UITextViewDelegate,MSStarControlDelegate>{
    UILabel *_placeHolder;
    CGFloat _contentHeight;
}

@property (nonatomic, weak) MBProgressHUD *progressHUD;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) MSStarControl *star;
@property (strong, nonatomic) UILabel *descLabel;
@property (strong, nonatomic) MSInputAttachView *attactView;
@property (strong, nonatomic) UILabel *inputRemind;
@property (strong, nonatomic) UIButton *punishButton;


@end

@implementation MSAddCommentDataSource

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initIngerface];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    }
    return self;
}

- (void)initIngerface {
    [self.scrollView addSubview:self.titleLabel];
    [self.scrollView addSubview:self.star];
    [self.scrollView addSubview:self.descLabel];
    [self.scrollView addSubview:self.textView];
    [self setupPlaceHolder];
    [self.textView addSubview:self.inputRemind];
    [self setRemindText];
    [self.scrollView addSubview:self.attactView];
    [self.scrollView addSubview:self.punishButton];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.scrollView).offset(30);
        make.centerX.equalTo(self.scrollView.mas_centerX);
    }];
    
    [self.star mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel.mas_bottom).offset(12);
        make.centerX.equalTo(self.scrollView);
        make.width.mas_equalTo(self.star.width);
        make.height.mas_equalTo(self.star.height);
    }];
    
    [self.descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.star.mas_bottom).offset(10);
        make.centerX.equalTo(self.scrollView);
    }];
    
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scrollView).offset(20);
        make.right.equalTo(self.scrollView).offset(-20);
        make.top.equalTo(self.descLabel.mas_bottom).offset(5);
        make.height.mas_equalTo(200);
    }];
    
    
    [self.attactView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.textView);
        make.top.equalTo(self.textView.mas_bottom).offset(20);
        make.height.mas_equalTo(70);
    }];
    
    [self.inputRemind mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.attactView).offset(-5);
        make.bottom.equalTo(self.attactView.mas_top).offset(-20);;
        make.height.mas_equalTo(33);
    }];
    
    [self.punishButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.attactView.mas_bottom).offset(50);
        make.left.equalTo(self.scrollView).offset(20);
        make.right.equalTo(self.scrollView).offset(-20);
        make.height.mas_equalTo(44);
        make.centerX.equalTo(self.scrollView);
    }];
    _contentHeight = MS_MAX_SCREEN_WIDTH - MS_NAVIGATION_HEIGHT - 100;
}

- (void)updateLayout {
    CGFloat textViewHeight = MIN(_contentHeight, 245) - self.attactView.attachViewHeight;
    textViewHeight = MAX(200, textViewHeight);  //textview最低108
    [self.textView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(textViewHeight);
    }];
    [self.attactView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.attactView.attachViewHeight);
    }];
}

- (void)setContent:(NSString *)content {
    self.textView.text = content;
    [self textViewDidChange:self.textView];
}

- (void)punishComment:(id)sender{
    if (![UserAccesser isLogin]) {
        [MBProgressHUD showToastWithMessage:@"您还未登录,不能对商家进行评论" toView:self.scrollView];
        return;
    }
    if (self.attactView.selectedPhotos.count > 0) {
        _WEAKSELF
        [MBProgressHUD showMessage:@"图片上传中"];
        [MSUserCenterDataSource queryUploadImageConfigWithSuccess:^(NSDictionary * _Nonnull responseInfo) {
            if ([MSSafeObject isNull:responseInfo]) {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showToastWithMessage:@"无效的token！" toView:weakSelf.scrollView];
                return ;
            }
            [weakSelf handleImage:responseInfo];
        } failure:^(NSError * _Nonnull error) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showToastWithMessage:@"图像上传失败，请稍后再试！" toView:weakSelf.scrollView];
        }];
    }
    else{
        [MBProgressHUD showMessage:@"提交中"];
        _WEAKSELF
        [self commentPunish:nil completion:^(BOOL success) {
            [MBProgressHUD hideHUD];
            if (success) {
                [[UIViewController currentViewController].navigationController popViewControllerAnimated:YES];
            }else{
                [MBProgressHUD showToastWithMessage:@"抱歉,评论发表失败,请稍后重试" toView:weakSelf.scrollView];
            }
        }];
    }
}

- (void)handleImage:(NSDictionary *)response {
    dispatch_group_t group = dispatch_group_create();
    __block BOOL success = YES;
    NSMutableArray *imgsArray = [NSMutableArray array];
    for (int index = 0 ; index < self.attactView.selectedPhotos.count; index++) {
        UIImage *image = self.attactView.selectedPhotos[index];
        dispatch_group_enter(group);
        [MSUploadImageUtils uploadImage:image withImageUpload:response bucketName:@"" resultBlock:^(NSDictionary *responseInfo) {
            
            dispatch_sync(dispatch_get_main_queue(), ^{
                if ([[MSSafeObject stringInfo:responseInfo[@"result"]] isEqualToString:@"1"]) {
                    if ([responseInfo objectForKey:@"photoname"]) {
                        [imgsArray addObject:[responseInfo objectForKey:@"photoname"]];
                    }
                }else{
                    success = NO;
                }
                dispatch_group_leave(group);
            });
        }];
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        if (success) {
            [self commentPunish:imgsArray completion:^(BOOL success) {
                [MBProgressHUD hideHUD];
                if (success) {
                    [[UIViewController currentViewController].navigationController popViewControllerAnimated:YES];
                }else{
                    [MBProgressHUD showToastWithMessage:@"图像上传失败，请稍后再试！" toView:self.scrollView];
                }
            }];
            
        }else{
            [MBProgressHUD hideHUD];
            [MBProgressHUD showToastWithMessage:@"图像上传失败，请稍后再试！" toView:self.scrollView];
        }
    });
}

- (void)commentPunish:(NSArray *)imgs completion:(void(^)(BOOL success))completion{
    NSNumber *mId = nil;
    NSNumber *kindId = nil;
    if ([self.data isKindOfClass:MSFoodDetailData.class]) {
        MSFoodDetailData *model = (MSFoodDetailData *)self.data;
        mId = model.mId;
        kindId = model.kind;
    }
    NSMutableDictionary *params = @{@"id":mId ?:@"",
                                    @"kindId":kindId ?:@(1),
                                    @"uid":[UserAccesser userId],
                                    @"score":@(self.star.scorePercent * 5),
                                    @"content":self.textView.text ?:@""}.mutableCopy;
    if (imgs.count > 0) {
        [params setObject:[imgs componentsJoinedByString:@","] forKey:@"imgs"];
    }
    [MSRequestClient POST:@"v1/comment/publish" parameters:params responseClassType:MappedModel.class responseCache:nil success:^(id responseObject) {
        if (completion) {
            completion(YES);
        }
    } failure:^(NSError *error) {
        if (completion) {
            completion(NO);
        }
    }];
}

#pragma mark - InputAttachViewDelegate

- (void)inputAttachView:(MSInputAttachView *)attachview changePublishType:(MSCommentPublishType)type {
}

- (void)inputAttachView:(MSInputAttachView *)attachview changeHeight:(CGFloat)height {
    [self updateLayout];
}

- (void)didFinishPickingPhotosWithAttachView:(MSInputAttachView *)attachView {
    [self.textView becomeFirstResponder];
}

#pragma mark - ScrollViewDelegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.textView endEditing:YES];
}

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    if (self.textView.text.length) {
        _placeHolder.hidden = YES;
    } else {
        _placeHolder.hidden = NO;
    }
    [self checkPublishEnable];
    [self setRemindText];
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    return YES;
}

- (void)checkPublishEnable {
    BOOL enable = NO;
    NSInteger textLength = self.textView.text.length;
    if (textLength >= MinCommentLength && textLength <= MaxCommentLength) {
        enable = YES;
    }
    if (enable != self.punishButton.enabled) {
        self.punishButton.enabled = enable;
        CGFloat alpha = enable ? 1 : 0.5;
        self.punishButton.backgroundColor = [UIColorHex(0xF96332) colorWithAlphaComponent:alpha];
    }
}

#pragma mark - notification
- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary*info=[notification userInfo];
    CGRect keyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
    _contentHeight = MS_MAX_SCREEN_WIDTH - MS_NAVIGATION_HEIGHT - 100 - keyboardRect.size.height;
    [self updateLayout];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    _contentHeight = MS_MAX_SCREEN_WIDTH - MS_NAVIGATION_HEIGHT - 100;
    [self updateLayout];
}

# pragma mark -MSStarControlDelegate
- (void)starControl:(MSStarControl *)starControl scorePercentDidChange:(CGFloat)newScorePercent{
    self.descLabel.text = [self getSatisfactionWithScore:newScorePercent];
    self.descLabel.hidden = NO;
}

- (NSString *)getSatisfactionWithScore:(CGFloat)scorePercent{
    NSString *satisfactionStr  = @"";
    if (scorePercent < 0.4) {
        satisfactionStr = @"不佳";
    }else if (scorePercent < 0.6){
        satisfactionStr = @"一般";
    }else if (scorePercent < 0.8){
        satisfactionStr = @"不错";
    }else if (scorePercent < 1){
        satisfactionStr = @"满意";
    }else{
        satisfactionStr = @"超级满意";
    }
    return satisfactionStr;
}
- (void)setRemindText{
    NSInteger inter = 15 - self.textView.text.length;
    if (inter > 0) {
        self.inputRemind.hidden = NO;
        self.inputRemind.text = [NSString stringWithFormat:@"加油,还差%ld个字!", inter];
    }else{
        self.inputRemind.hidden = YES;
    }
    
}

#pragma mark - Property
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.alwaysBounceVertical = YES;
        _scrollView.delegate = self;
    }
    return _scrollView;
}
- (UILabel *)titleLabel{
    if (!_titleLabel) {
        _titleLabel = [UILabel new];
        _titleLabel.font = [UIFont boldSystemFontOfSize:16];
        _titleLabel.text = @"商家评价";
        _titleLabel.textColor = UIColorHex(0x444444);
    }
    return _titleLabel;
}


- (MSStarControl *)star{
    if (!_star) {
        _star = [[MSStarControl alloc] initWithFrame:CGRectMake(0, 0, 181, 25) numberOfStars:5 image:@"Greystar_Comments" foreColor:UIColorHex(0xFFC700) backColor:UIColorHex(0xdddddd)];
        _star.allowScore = YES;
//        _star.allowIncompleteStar = YES;
        _star.delegate = self;
        _star.scorePercent = 0;
    }
    return _star;
}

- (UILabel *)descLabel{
    if (!_descLabel) {
        _descLabel = [UILabel new];
        _descLabel.font = [UIFont systemFontOfSize:12];
        _descLabel.textColor = UIColorHex(0xF96332);
        _descLabel.text = @"满意";
        _descLabel.hidden = YES;
    }
    return _descLabel;
}

- (UITextView *)textView {
    if (!_textView) {
        _textView = [[UITextView alloc] init];
        _textView.delegate = self;
        _textView.font = [UIFont systemFontOfSize:14];
        _textView.textColor = UIColorHex(0x444444);
        _textView.backgroundColor = UIColorHex(0xdddddd);
    }
    return _textView;
}

- (void)setupPlaceHolder {
    _placeHolder = [[UILabel alloc] init];
    _placeHolder.text = @"写下您的体验吧～";
    _placeHolder.textColor = [UIColor lightGrayColor];
    _placeHolder.numberOfLines = 0;
    _placeHolder.contentMode = UIViewContentModeTop;
    _placeHolder.font = self.textView.font;
    [self.textView addSubview:_placeHolder];
    [_placeHolder mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.textView).offset(5);
        make.top.right.equalTo(self.textView);
        make.height.mas_equalTo(33);
    }];
}

- (UILabel *)inputRemind {
    if (!_inputRemind) {
        _inputRemind = [[UILabel alloc] init];
        _inputRemind.textColor = [UIColor lightGrayColor];
        _inputRemind.numberOfLines = 0;
        _inputRemind.contentMode = UIViewContentModeTop;
        _inputRemind.font = self.textView.font;
    }
    return _inputRemind;
    
}

- (MSInputAttachView *)attactView {
    if (!_attactView) {
        _attactView = [[MSInputAttachView alloc] init];
        _attactView.delegate = self;
    }
    return _attactView;
}

-(UIButton *)punishButton{
    if (!_punishButton) {
        _punishButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _punishButton.layer.cornerRadius = 22;
        _punishButton.clipsToBounds = YES;
        _punishButton.backgroundColor = [UIColorHex(0xF96332) colorWithAlphaComponent:0.5];
        [_punishButton setTitle:@"发表评论" forState:UIControlStateNormal];
        [_punishButton addTarget:self action:@selector(punishComment:) forControlEvents:UIControlEventTouchUpInside];
//        _punishButton.enabled = NO;
        _punishButton.enabled = YES;
        
    }
    return _punishButton;
}

- (NSString *)title{
    if (!_title) {
        if ([self.data isKindOfClass:MSFoodContentModel.class]) {
            _title = ((MSFoodContentModel *)self.data).title;
        }
    }
    return _title;
    
}
@end
